package com.xuanzheng.company.dao.impl;

import com.xuanzheng.company.dao.SystemApplicationDao;
import com.xuanzheng.company.entity.SystemApplication;
import com.xuanzheng.company.util.DBUtil;
import com.xuanzheng.company.util.IdGenerator;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class SystemApplicationDaoImpl implements SystemApplicationDao {

    @Override
    public boolean addApplication(SystemApplication application) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        boolean result = false;

        try {
            conn = DBUtil.getConnection();
            String sql = "INSERT INTO system_application (id, user_id, user_name, user_phone, company_name, company_credit_code, reason, status) " +
                    "VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
            pstmt = conn.prepareStatement(sql);

            // 生成唯一ID
            String id = IdGenerator.generateId();
            application.setId(id);

            pstmt.setString(1, application.getId());
            pstmt.setString(2, application.getUserId());
            pstmt.setString(3, application.getUserName());
            pstmt.setString(4, application.getUserPhone());
            pstmt.setString(5, application.getCompanyName());
            pstmt.setString(6, application.getCompanyCreditCode());
            pstmt.setString(7, application.getReason());
            pstmt.setInt(8, 0); // 默认状态为待审核

            int affectedRows = pstmt.executeUpdate();
            result = (affectedRows > 0);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt, null);
        }

        return result;
    }

    @Override
    public boolean updateApplicationStatus(String id, int status, String rejectReason) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        boolean result = false;

        try {
            conn = DBUtil.getConnection();
            String sql;
            if (status == 2 && rejectReason != null && !rejectReason.isEmpty()) {
                // 拒绝申请，需要填写拒绝原因
                sql = "UPDATE system_application SET status = ?, reject_reason = ? WHERE id = ?";
                pstmt = conn.prepareStatement(sql);
                pstmt.setInt(1, status);
                pstmt.setString(2, rejectReason);
                pstmt.setString(3, id);
            } else {
                // 其他状态变更
                sql = "UPDATE system_application SET status = ? WHERE id = ?";
                pstmt = conn.prepareStatement(sql);
                pstmt.setInt(1, status);
                pstmt.setString(2, id);
            }

            int affectedRows = pstmt.executeUpdate();
            result = (affectedRows > 0);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt, null);
        }

        return result;
    }

    @Override
    public SystemApplication getApplicationById(String id) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        SystemApplication application = null;

        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT * FROM system_application WHERE id = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, id);
            rs = pstmt.executeQuery();

            if (rs.next()) {
                application = extractApplicationFromResultSet(rs);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt, rs);
        }

        return application;
    }

    @Override
    public List<SystemApplication> getApplicationsByUserId(String userId) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        List<SystemApplication> applications = new ArrayList<>();

        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT * FROM system_application WHERE user_id = ? ORDER BY create_time DESC";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, userId);
            rs = pstmt.executeQuery();

            while (rs.next()) {
                SystemApplication application = extractApplicationFromResultSet(rs);
                applications.add(application);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt, rs);
        }

        return applications;
    }

    @Override
    public SystemApplication getLatestApplicationByUserId(String userId) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        SystemApplication application = null;

        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT * FROM system_application WHERE user_id = ? ORDER BY create_time DESC LIMIT 1";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, userId);
            rs = pstmt.executeQuery();

            if (rs.next()) {
                application = extractApplicationFromResultSet(rs);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt, rs);
        }

        return application;
    }

    @Override
    public List<SystemApplication> getAllApplications() {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        List<SystemApplication> applications = new ArrayList<>();

        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT * FROM system_application ORDER BY create_time DESC";
            pstmt = conn.prepareStatement(sql);
            rs = pstmt.executeQuery();

            while (rs.next()) {
                SystemApplication application = extractApplicationFromResultSet(rs);
                applications.add(application);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt, rs);
        }

        return applications;
    }

    @Override
    public List<SystemApplication> getApplicationsByStatus(int status) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        List<SystemApplication> applications = new ArrayList<>();

        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT * FROM system_application WHERE status = ? ORDER BY create_time DESC";
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, status);
            rs = pstmt.executeQuery();

            while (rs.next()) {
                SystemApplication application = extractApplicationFromResultSet(rs);
                applications.add(application);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt, rs);
        }

        return applications;
    }

    @Override
    public List<SystemApplication> searchApplications(String keyword) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        List<SystemApplication> applications = new ArrayList<>();

        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT * FROM system_application WHERE user_name LIKE ? OR user_phone LIKE ? OR id LIKE ? ORDER BY create_time DESC";
            pstmt = conn.prepareStatement(sql);
            String searchKeyword = "%" + keyword + "%";
            pstmt.setString(1, searchKeyword);
            pstmt.setString(2, searchKeyword);
            pstmt.setString(3, searchKeyword);
            rs = pstmt.executeQuery();

            while (rs.next()) {
                SystemApplication application = extractApplicationFromResultSet(rs);
                applications.add(application);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt, rs);
        }

        return applications;
    }

    @Override
    public List<SystemApplication> searchApplicationsWithStatus(int status, String keyword) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        List<SystemApplication> applications = new ArrayList<>();

        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT * FROM system_application WHERE status = ? AND (user_name LIKE ? OR user_phone LIKE ? OR id LIKE ?) ORDER BY create_time DESC";
            pstmt = conn.prepareStatement(sql);
            String searchKeyword = "%" + keyword + "%";
            pstmt.setInt(1, status);
            pstmt.setString(2, searchKeyword);
            pstmt.setString(3, searchKeyword);
            pstmt.setString(4, searchKeyword);
            rs = pstmt.executeQuery();

            while (rs.next()) {
                SystemApplication application = extractApplicationFromResultSet(rs);
                applications.add(application);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt, rs);
        }

        return applications;
    }

    // 辅助方法：从ResultSet中提取SystemApplication对象
    private SystemApplication extractApplicationFromResultSet(ResultSet rs) throws SQLException {
        SystemApplication application = new SystemApplication();
        application.setId(rs.getString("id"));
        application.setUserId(rs.getString("user_id"));
        application.setUserName(rs.getString("user_name"));
        application.setUserPhone(rs.getString("user_phone"));
        application.setCompanyName(rs.getString("company_name"));
        application.setCompanyCreditCode(rs.getString("company_credit_code"));
        application.setReason(rs.getString("reason"));
        application.setStatus(rs.getInt("status"));
        application.setRejectReason(rs.getString("reject_reason"));
        application.setCreateTime(rs.getTimestamp("create_time"));
        application.setUpdateTime(rs.getTimestamp("update_time"));
        return application;
    }
} 